package com.cos.web.controller;

import com.cos.entity.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author: COS
 * @time: 2021/11/17 9:26
 * @description:
 */
//@Controller
@RestController//@COntroller+@reponseBody 默认这个controller下面所有方法都自动带上@responseBody这个注解
@RequestMapping("/user")
public class UserController {
    List<User> ulist = new ArrayList<>();

    public UserController() {
       for(int i=0;i<10;i++){
           ulist.add(new User(i+1,"张"+i,"男",new Date(),123.23333333));
       }
    }
    /**
     *
     * @author: COS
     * @return:
     * @time: 2021/11/17 10:11
     * @description: 接受json数据
     */
    @RequestMapping("/add")
    public String addUser(@RequestBody User user){
        System.out.println(10/0);
        System.out.println(user);
        return "ok";
    }
    /**
     *
     * @author: COS
     * @return:
     * @time: 2021/11/17 10:28
     * @description: method = RequestMethod.GET  用于指定本请求方法,接受请求时,指定只能使用get请求,
     */
    @RequestMapping(value = "/getAll",method = RequestMethod.GET)
//    @ResponseBody
    public List<User> getAll(){
        return ulist;
    }
    @RequestMapping("/getAll2")
//    @ResponseBody
    public String getAll2() throws IOException {
        ObjectMapper om = new ObjectMapper();
//        String user="";
//        User user1 = om.readValue(user, User.class);
        return om.writeValueAsString(ulist);
    }


    @RequestMapping("/getUserByUno")
//    @ResponseBody
    public User getUserByUno(int uno){
//        List<User> collect = ulist.stream().filter(x -> x.getUno() == uno).map(x -> new User(x.getUno(), x.getUname(), x.getUsex(), x.getBornDate())).collect(Collectors.toList());
        User collect = ulist.stream().filter(x -> x.getUno() == uno)
                .map(x -> new User(x.getUno(), x.getUname(), x.getUsex(), x.getBornDate()))
                .findAny().orElse(null);
        return collect;
    }


    @RequestMapping("/getUserByJson")
//    @ResponseBody
    public User getUserBuJson(){
        return new User(1, "张三","男",new Date());
    }

}
